package com.example.musicplayer;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.database.Cursor;
import android.icu.text.SimpleDateFormat;
import android.media.Image;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;

public class MusicList extends AppCompatActivity implements View.OnClickListener {
    ImageView nextIv,playIv,lastIv;
    TextView singerTv,songTv;
    ImageView bottomIv;
    RecyclerView musicRv;
    List<LocalMusicBean>musicDatas;
    ObjectAnimator animator ;
    ImageView albumIv;
//    SeekBar seekBar;
    TextView current_time,length_time;
//    Timer timer;
//    boolean isSeekingChanging;

    private LocalMusicAdapter adapter;
    int sum ;


    int playingPosition = -1;
    MediaPlayer mediaPlayer;

    int pausePlayingPosition=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.music_list);
        initView();
        mediaPlayer = new MediaPlayer();
        musicDatas = new ArrayList<>();

        adapter = new LocalMusicAdapter(this,musicDatas);
        musicRv.setAdapter(adapter);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);//竖直滑动
        musicRv.setLayoutManager(layoutManager);

        loadLocalMusicDatas();


        setEventListener();

    }

    public void setEventListener(){
        adapter.setOnItemClickListener(new LocalMusicAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, int position) {
                playingPosition = position;
                LocalMusicBean musicBean = musicDatas.get(position);
                playMusicInMusicBean(musicBean);
                animator.start();
            }
        });
    }


    public void playMusicInMusicBean(LocalMusicBean musicBean) {
        singerTv.setText(musicBean.getSinger());
        songTv.setText(musicBean.getSong());
        length_time.setText(musicBean.getDuration());

        stopMusic();
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(musicBean.getPath());
            playmusic();
//            seekBar.setMax(Integer.parseInt(musicBean.getDuration()));
        }catch (IOException e){
            e.printStackTrace();
        }
    }



    private void pauseMusic() {
        if(mediaPlayer!=null && mediaPlayer.isPlaying()){
            pausePlayingPosition = mediaPlayer.getCurrentPosition();
            mediaPlayer.pause();
            playIv.setImageResource(R.drawable.icon_stop);
        }
    }

    private void playmusic() {
        if (mediaPlayer!=null && !mediaPlayer.isPlaying()){
            if(pausePlayingPosition == 0){
            try {
                mediaPlayer.prepare();
                mediaPlayer.start();
            } catch (IOException e) {
                e.printStackTrace();
            }}else{
                mediaPlayer.seekTo(pausePlayingPosition);
                mediaPlayer.start();
            }
            playIv.setImageResource(R.drawable.icon_stop);
        }
    }


    private void stopMusic(){
        if (mediaPlayer!= null){
            pausePlayingPosition = 0;
            mediaPlayer.pause();
            mediaPlayer.seekTo(0);
            mediaPlayer.stop();
            playIv.setImageResource(R.drawable.icon_play);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopMusic();
    }

    private void loadLocalMusicDatas(){
        ContentResolver resolver = getContentResolver();
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        Cursor cursor = resolver.query(uri,null,null,null,null);

        int id = 0;
        while(cursor.moveToNext()){
            @SuppressLint("Range") String song = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            @SuppressLint("Range")String singer = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            @SuppressLint("Range")String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
            id++;
            String sid = String.valueOf(id);
            @SuppressLint("Range")String path= cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            @SuppressLint("Range")long duration= cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
            SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
            String time = sdf.format(new Date(duration));

            if(time.equals("00:00")){
                Log.d("notmp3", "loadLocalMusicDatas: 不是MP3");
                id--;
            }else {
                LocalMusicBean bean = new LocalMusicBean(sid, song, singer, album, time, path);
                musicDatas.add(bean);
            }
        }
        sum = id;
        adapter.notifyDataSetChanged();
    }

    private void initView() {
        nextIv = findViewById(R.id.bottom_next);
        playIv = findViewById(R.id.bottom_play);
        lastIv = findViewById(R.id.bottom_last);
        singerTv = findViewById(R.id.music_bottom_singer_text);
        songTv = findViewById(R.id.music_bottom_song_text);
        musicRv = findViewById(R.id.localmusic_recyclerview);
        current_time =findViewById(R.id.current_time);
        length_time = findViewById(R.id.length_time);

//        seekBar = findViewById(R.id.seekbar);

        nextIv.setOnClickListener(this);
        lastIv.setOnClickListener(this);
        playIv.setOnClickListener(this);

        bottomIv = findViewById(R.id.music_botton_icon_song);


        animator = ObjectAnimator.ofFloat(bottomIv, "rotation", 0.0f, 360.0f);
        animator.setDuration(10000);
        animator.setInterpolator(new LinearInterpolator());
        animator.setRepeatCount(-1);
        animator.setRepeatMode(ValueAnimator.RESTART);

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.bottom_last:
                 if(playingPosition ==-1){
                     Toast.makeText(this, "没有选择音乐", Toast.LENGTH_SHORT).show();
                     return;
                 }
                 if(playingPosition == 0){
                     playingPosition = sum-1;
                     LocalMusicBean lastBean = musicDatas.get(playingPosition);
                     playMusicInMusicBean(lastBean);
                 }else{
                     playingPosition = playingPosition-1;
                     LocalMusicBean lastBean = musicDatas.get(playingPosition);
                     playMusicInMusicBean(lastBean);
                 }

                break;
            case R.id.bottom_play:
                if(playingPosition==-1){
                    Toast.makeText(this, "没有选择音乐", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(mediaPlayer.isPlaying()){
                    pauseMusic();
                    playIv.setImageResource(R.drawable.icon_play);
//                    setPlaying(mediaPlayer.isPlaying(),animator);
                    animator.pause();
                }else{
                    playmusic();
                    animator.resume();
                }
                break;
            case R.id.bottom_next:
                if(playingPosition ==-1){
                    Toast.makeText(this, "没有选择音乐", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(playingPosition+1 == sum){
                    playingPosition = 0;
                    LocalMusicBean lastBean = musicDatas.get(playingPosition);
                    playMusicInMusicBean(lastBean);
                }else{
                    playingPosition = playingPosition + 1;
                    LocalMusicBean lastBean = musicDatas.get(playingPosition);
                    playMusicInMusicBean(lastBean);
                }

                break;
        }
    }}
//class MySeekbar implements OnSeekBarChangeListener {
//    public void onProgressChanged(SeekBar seekBar, int progress,
//                                  boolean fromUser) {
//    }
//
//    public void onStartTrackingTouch(SeekBar seekBar) {
//        isChanging=true;
//    }
//
//    public void onStopTrackingTouch(SeekBar seekBar) {
//        player.seekTo(seekbar.getProgress());
//        isChanging=false;
//    }
//
//}

